package com.raycloud.util;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.output.ByteArrayOutputStream;

import java.io.*;

/**
 * Created by donar on 17/4/19.
 */
public class CmdUtil {
    public static String exec(String command) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            CommandLine commandline = CommandLine.parse(command);
            DefaultExecutor exec = new DefaultExecutor();
            exec.setExitValues(null);
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
            exec.setStreamHandler(streamHandler);
            exec.execute(commandline);
            String out = outputStream.toString("UTF-8").replaceAll("\n", "</br>");
            String error = errorStream.toString("UTF-8").replaceAll("\n", "</br>");
            return out + "</br></br></br>" + error;
        } catch (Exception e) {
            return e.toString();
        }
    }


    public static void  execv(String command,PrintWriter writer) throws IOException {
        Process process = null;
        process = Runtime.getRuntime().exec(command);
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = input.readLine()) != null) {
            writer.println(line+"<br/>");
            writer.flush();
        }
        input.close();
    }
}
